/*
 * MKeyPlus
 * BaseApp基座
 * @version 1.0 
 * @time 2017-9-7 16:19:41
 */
(function($){
	if(!$){
		console.log("引用的时，必须先引用mui.min.js！!!");
	}
	var BaseApp = function(){
		
	};
	var retimeout = 60000; //超时时间
	var Token=localStorage.getItem("token");
	window.G_Config = function(){
		var config = {
			host:'neom.cgnpc.com.cn',
			// host:'10.8.3.98:8088',

			protocol:'https://',
			// protocol:'http://',
			WLRY_path:'/server-api',//外来人员服务路径
			// WLRY_path:'',//外来人员服务路径
			YJYD_path:'/smartreport-api/ddmsapp',//一机一档服务路径
			XJ_path:'/smartreport-api/ydxj',

			LP_path:'/smartreport-api',//两票服务路径
		}
		localStorage.setItem('baseConfig',JSON.stringify(config))
		return config
	}
	var bCg = window.G_Config()
	console.log("Bearer " + Token)

    var ip = bCg.host + bCg.WLRY_path;
    // ip ='10.8.3.118:8099';
	//服务器IP
	BaseApp.prototype.serverUrl =  bCg.protocol + ip;//
	//BaseApp.prototype.serverUrl = "http://" + ip;//
	//客户段appid  mkeyplus分配
	BaseApp.prototype.AppId = "7d52fbba712b407b9f2f49e3f84be4db";
	BaseApp.prototype.AppKey = "fd";
	BaseApp.prototype.AppSecret = "fd";
	
	/**
	 * 打开模块，首先判断是否有文件，如果有文件则打开，没有则下载wgt安装 
	 * 默认webview的id和页面路径一致，
	 * @param {url} string 页面相对跟目录的全路径   例如：/index2.html
	 * @param {extras} object 页面传参 {name:'mui',version:'0.5.8'}
	 */
	BaseApp.prototype.startModel = function(url,extras){
		//检查文件是否存在
		checkPath(url,extras) 
		//extras:
	}
	
	//打开新页面
	BaseApp.prototype.openWindow = function(url,extras,subpages,show){
		//统一路由管理   
		//目前还没有添加权限
		//
		
		
		//打开新页面
		mui.openWindow({
			url: url,
			id: (url.indexOf("?")>0)?(url.substring(0,url.indexOf("?"))):url,
			show: show?show:{
				autoShow: true,
				aniShow: "slide-in-right",
				duration: '200' //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
			},
			waiting: {
				autoShow: false
			},
			subpages:subpages?subpages:{},
			extras:extras?extras:{}
		});
	}
	
	/**
	 * 检查版本更新 
	 * @param {success} 成功回调方法
	 */
	BaseApp.prototype.checkUpdate = function(success,error){
		//获取当前版本号
		plus.runtime.getProperty(plus.runtime.appid,function(inf){
		 	//判断是否有忽略的版本
		 	var temp = inf.version;
		 	localStorage.setItem("currVersion",temp);
	      	var param = {
				version:temp
			}
	      	$.baseApp.httpRequst("/api/v2/appVer/checkNewVersion",param,
			function(data){
				console.log(JSON.stringify(data));
				if(data.status == "200"){ 
					success(data.data);
				}else{
					plus.nativeUI.toast(data.message);
					console.log(data.message);
				}
				
			},error,'post');
	    });
	}
	
	/**
	 * 安装wgt
	 * @param {filePath} string 文件路径
	 */
	BaseApp.prototype.install = function(filePath){
		plus.runtime.install(filePath,{force: true},function(){
		        plus.runtime.restart();
		    },function(e){
		    	console.log("更新安装失败");
		    });
	}
	
	
	/**
	 * http请求
	 * @param {url} 请求地址
	 * @param {param} http请求参数
	 * @param {type} get|post 默认是get
	 * @param {success} 成功回调
	 * @param {error}  失败回调
	 */
	BaseApp.prototype.httpRequst = function(url,param,success,error,type){
		console.log(url)
		if(!/^http/.test(url)){
			url = this.serverUrl+url;
		}
    // console.log(JSON.stringify(param))
		param = param?param:{};
		param.AppId = this.AppId;
		param.AppKey = this.AppKey;
		param.AppSecret = this.AppSecret;
		// param.version   = "1.0";
		param.userid = "2";
		// 第一次登陆的时候没有获取到userid
		if(!localStorage.getItem("userid") || localStorage.getItem("userid")=="undefined"){
			param.userid = "1038";
			localStorage.setItem("userid",param.userid);
		}else{
			param.userid = localStorage.getItem("userid")
			// console.log(typeof param.userid)
			// console.log(param.userid)
		}
		param.timestamp = new Date().getTime();
		param.OSType = (mui.os.ios)?"ios":"android";
		if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE){
      plus.nativeUI.closeWaiting()
		  return;
		}
		if(localStorage.getItem("uuid") == null || localStorage.getItem("uuid") == ""){
			// 获取设备信息
      var getDeviceInfo = function(){
        plus.device.getInfo({
        	success: function(e) {
        		param.DGUID = e.uuid;
        		localStorage.setItem("uuid", e.uuid);
        		
        		console.log("ajax_url: " + url);
        		console.log("ajax_param: " + JSON.stringify(param));
        		console.log("ajax_param: " + type);
        		console.log(localStorage.getItem("userid"));
        		
        		// 添加固定参数
        		mui.ajax(url, {
        			data: param,
        			dataType: 'json', //服务器返回json数据
        			type: type?type:"get", //http请求类型
					headers: {"token":localStorage.getItem("token")},
        			timeout: retimeout,
        			processData: type=='put'?false:true,
        			success: function(data) {
        				success(data);
                
        			},
        			error: function(xhr, type, errorThrown,data) {
        				console.log(xhr+""+data); 
        				console.log(type);
        				console.log(errorThrown);
        				console.log(typeof(error));
                console.log("ajax_url: " + url);
        				if(typeof(error) == "function"){
        					error(errorThrown,xhr);
        				}
        			}
        		});
        	},
        	fail: function(e) {
            getDeviceInfo()
        		console.log('getDeviceInfo failed: '+JSON.stringify(e));
        	}
        });
      }
			getDeviceInfo()
		} else {
			param.DGUID = localStorage.getItem("uuid");
			
			console.log("ajax_url: " + url);
			console.log("ajax_param: " + JSON.stringify(param));
			console.log("ajax_param: " + param.version);
			console.log("ajax_param: " + type);
			console.log(localStorage.getItem("userid"));
			if(type=='put'){
        mui.ajax(url, {
        	data: JSON.stringify(param),
        	dataType: 'json', //服务器返回json数据
        	type:"put", //http请求类型
          headers: {'Content-Type':'application/json'},
          // headers:{'Content-Type':'application/json'},
        	timeout: retimeout,
          processData: type=='put'?false:true,
        	success: function(data) {
        		success(data);
            console.log('成功');
        	},
        	error: function(xhr, type, errorThrown) {
        		console.log(JSON.stringify(xhr)+""); 
        		console.log(type);
            //mui.toast(JSON.parse(xhr.responseText).message)
        		if(typeof(error) == "function"){
        			error(errorThrown,xhr);
        		}
        	}
        });
        return
      }
      if (type == 'post') {
        mui.ajax(url, {
          data: JSON.stringify(param),
          dataType: 'json', //服务器返回json数据
          type: "post", //http请求类型
          headers: {
            'Content-Type': 'application/json',
            "token": localStorage.getItem("token")
          },
          crossDomain: true,
          timeout: retimeout,
          // processData: type=='put'?false:true,
          success: function (data) {
            success(data);
          },
          error: function (xhr, type, errorThrown) {
            console.log(JSON.stringify(xhr) + "");
            console.log(type);
            console.log(errorThrown);
            console.log('111111111' + xhr.responseText);
            console.log(typeof (error));
            // mui.toast(JSON.parse(xhr.responseText).message)
            if (typeof (error) == "function") {
              error(type, xhr);
            }
          }
        });
        return
      }
      // 添加固定参数
      mui.ajax(url, {
        data: param,
        dataType: 'json', //服务器返回json数据
        type: type ? type : "get", //http请求类型
        headers: { "token": localStorage.getItem("token") },
        timeout: retimeout,
        success: function (data) {
          success(data);
        },
        error: function (xhr, type, errorThrown) {
          console.log(JSON.stringify(xhr.responseText) + "");
          console.log(type);
          console.log(errorThrown);
          console.log(typeof (error));
          console.log('-------' + localStorage.getItem("token"));
          if (plus.networkinfo.getCurrentType() != plus.networkinfo.CONNECTION_NONE) {

            error(errorThrown, xhr)
          }

          if (typeof (error) == "function") {
            error(errorThrown, xhr);
          }
        }
      });
    }
  }

  /**
   * 根据文件判断模块是否已经加载
   * @param {path} string 文件路径  相对路径 /pages/index.html
   * @return 如果存在则返回true,否则false
   */
  function checkPath (path) {
    var this_ = this;
    if (!path) {
      console.log("path不存在，下载对应的模块升级包");
      this.download()
    }
    plus.io.resolveLocalFileSystemURL("_www" + path, function () {
      this_.openWindow("_www" + path);
    }, function (error) {
      console.log("error：" + JSON.stringify(error));
    });
  }


  //	BaseApp.prototype.download = function(url,progressbar){
  //		// 下载wgt文件
  //	    console.log(url.indexOf("http://"));
  //	    //判断是否是完整URL
  //	    if(url.indexOf("http://") <0){//相对url
  //	    	url = this.serverUrl+url;
  //	    }
  //	    console.log("升级包地址："+url);
  //	  	var dtask = plus.downloader.createDownload( url, {filename:"_doc/update/"}, function(d,status){
  //	        if ( status == 200 ) { 
  //	        	console.log("下载完成");
  ////	            installWgt(d.filename); // 安装wgt包
  //	        } else {
  //	            console.log("下载更新失败！");
  //	            alert("下载更新失败！");
  //	            cancelupdate();//自动登录或者进入主页
  //	        }
  //	    });
  //	    //监听下载状态
  //	    dtask.addEventListener( "statechanged", function(task,status){
  //	    	if(!dtask){return;}
  //	    	console.log("==========下载===========");
  //	    	switch(task.state) {
  //	    		case 1: // 开始
  //	    			console.log( "开始下载..." );
  //	    			break;
  //	    		case 2: // 已连接到服务器
  //	    			console.log( "链接到服务器..." );
  //	    			break;
  //	    		case 3:	// 已接收到数据
  //	    			var jindu = percentNum(task.downloadedSize,task.totalSize);
  //	    			progressbar.setProgress(jindu);
  ////	    			document.getElementById("progressNumber").innerText=""+jindu+"%";
  //	    			break;
  //	    		case 4:	// 下载完成
  ////	    			$("#loading").css("display","block");//loading显示
  ////	    			document.getElementById("progressNumber").innerText = "下载完成！";
  ////	    			setTimeout(function(){
  ////	    				document.getElementById("progressNumber").innerText = "正在安装！";
  ////	    			},300)
  //	    			console.log( task.totalSize );
  //	    			break;
  //	    	}
  //	    } );
  //	    dtask.start();
  //	}
  $.baseWApp = new BaseApp();
})(mui);
